package com.xiaouyudeguang.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Data
@Slf4j
@Configuration
@EnableCaching
@ConfigurationProperties("cache")
@ConditionalOnClass(StringRedisSerializer.class)
public class CacheConfig {

    private long globalCacheTime = 300L;

    private Map<String, Long> cacheTimes = new HashMap<>();

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(new JavaTimeModule());
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化（解决乱码的问题）
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(globalCacheTime))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
        Map<String, RedisCacheConfiguration> cacheConfig = new HashMap<>();
        if (cacheTimes != null && !cacheTimes.isEmpty()) {
            cacheTimes.forEach((cacheName, expireTime) -> {
                cacheConfig.put(cacheName,
                        RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(expireTime))
                                .serializeKeysWith(
                                        RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                                .serializeValuesWith(RedisSerializationContext.SerializationPair
                                        .fromSerializer(jackson2JsonRedisSerializer)));
            });
            log.info("cacheConfig.{}", cacheConfig);
        }
        return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config)
                .withInitialCacheConfigurations(cacheConfig).build();
    }
}
